package com.chinalin.h5_webrtc_host

import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity

class SplashActivity : AppCompatActivity() {

    // 统一处理App权限请求
    private val requestMultiplePermissions =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            val results = permissions.entries
            val failedItems = results.filter { it.value.not() }
            if (failedItems.isNotEmpty()) {
                Toast.makeText(
                    this,
                    "部分权限请求不成功，请重新进入本页面：${failedItems.map { it.key }}",
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                finish()
                MainActivity.start(this)
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
        requestAppPermissions()
    }

    private fun requestAppPermissions() {
        val permissionsToRequest = listOfNotNull(
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.RECORD_AUDIO,
            android.Manifest.permission.ACCESS_FINE_LOCATION,
            // 根据Android版本决定是否需要存储权限
            if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.P) {
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE
            } else null
        )
        if (permissionsToRequest.isNotEmpty()) {
            requestMultiplePermissions.launch(permissionsToRequest.toTypedArray())
        }
    }
}